package benny_driving_ser.dao.impl;

import java.lang.ref.SoftReference;
import java.net.URI;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import atg.taglib.json.util.JSONException;
import atg.taglib.json.util.JSONObject;
import benny_driving_ser.constant.URLConstant;
import benny_driving_ser.dao.LoginDao;
import benny_driving_ser.entity.DriLogin;
import benny_driving_ser.entity.SessionAttributeDriId;
import benny_driving_ser.util.DBUtil;
import benny_driving_ser.util.SendSMSUtil;

@SuppressWarnings("deprecation")
public class LoginDaoImpl implements LoginDao {
	private static LinkedHashMap<String, SoftReference<String>> mSoftCache;

	private LoginDaoImpl() {
		mSoftCache = new LinkedHashMap<String, SoftReference<String>>(256,
				0.75f, true) {
			private static final long serialVersionUID = 233805867382515258L;

			@Override
			protected boolean removeEldestEntry(
					Entry<String, SoftReference<String>> eldest) {
				if (size() > 256) {
					return true;
				}
				return false;
			}
		};
	}

	private static class LoginDaoImplHolder {
		private static LoginDaoImpl instance = new LoginDaoImpl();
	}

	public static LoginDaoImpl getInstance() {
		return LoginDaoImplHolder.instance;
	}

	public DriLogin driStateInfo(String driid) {
		System.out.println(driid);
		String sql_query_perInfo = "SELECT t_user.xynf,t_user.state,t_user.ye,t_user.ispay,t_sj_xy.sjuserid FROM t_user LEFT JOIN t_sj_xy ON t_user.id = t_sj_xy.sjuserid WHERE t_user.id = ?";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			PreparedStatement ps = con.prepareStatement(sql_query_perInfo);
			ps.setString(1, driid);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				String dateOfSignProtocol = rs.getString(1);
				int state = rs.getInt(2);
				double balance = rs.getDouble(3);
				int isPay = rs.getInt(4);
				String driIdFromLoc = rs.getString(5);
				int isAgr = 1, isTopup = 1, pState = 1;
				if (balance > 99)
					isTopup = 0;
				if (null != dateOfSignProtocol)
					if (System.currentTimeMillis()
							- Long.parseLong(dateOfSignProtocol) < 365 * 24
							* 60 * 60 * 1000)
						isAgr = 0;
					else
						isAgr = 2;// 协议过期
				if (null != driIdFromLoc)
					pState = 0;
				return new DriLogin(isAgr, isTopup, state, pState, isPay, 0);
			}
			return new DriLogin(1);

		} catch (SQLException e) {
			e.printStackTrace();
			return new DriLogin(2);
		} finally {
			DBUtil.getInstance().closeConnection(con);
		}
	}

	public SessionAttributeDriId driLogin(String acc, String psd) {
		String sql_query = "SELECT id,pwd_version FROM t_user WHERE username = ? AND userpwd = ?";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			PreparedStatement ps = con.prepareStatement(sql_query);
			ps.setString(1, acc);
			ps.setString(2, psd);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				return new SessionAttributeDriId(rs.getString(1),
						rs.getString(2));
				// return rs.getString(1);
			}
			return new SessionAttributeDriId("1", "0");
		} catch (SQLException e) {
			e.printStackTrace();
			return new SessionAttributeDriId("2", "0");
		} finally {
			DBUtil.getInstance().closeConnection(con);
		}

	}

	public int signProtocol(int agrid, int driid) {
		String sql_update = "UPDATE t_user SET xynf = '"
				+ System.currentTimeMillis() + "' WHERE id = " + driid;
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			Statement s = con.createStatement();
			int res = s.executeUpdate(sql_update);
			if (res != 0) {
				DBUtil.getInstance().closeConnection(con);
				return 0;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtil.getInstance().closeConnection(con);
		return 1;
	}

	public int vcReg(String tel) {
		Random r = new Random();
		int type = 0;
		int n = 0;
		String line = "";
		for (int i = 0; i < 5; i++) {
			type = r.nextInt(2);
			switch (type) {
			case 0:
				n = r.nextInt(10);
				break;
			case 1:
				n = r.nextInt('z' - 'a' + 1) + 'a';
				break;
			case 2:
				n = r.nextInt('Z' - 'A' + 1) + 'A';
				break;
			}
			if (type == 0) {
				line += n;
			} else {
				line += (char) n;
			}
		}
		try {
			// String url = URLConstant.SMS_BASE_URL + "smsMob=" + tel
			// + "&smsText=" + URLEncoder.encode("上海邦尼驾驶短信验证码：", "gbk")
			// + line + URLEncoder.encode("，20分钟内有效哟~ >_<", "gbk");
			// DefaultHttpClient httpClient = new DefaultHttpClient();
			// HttpGet httpGet = new HttpGet();
			// httpGet.setURI(new URI(url));
			// HttpResponse httpresponse = httpClient.execute(httpGet);
			// HttpEntity entity = httpresponse.getEntity();
			// String res = EntityUtils.toString(entity);
			if (SendSMSUtil.getInstance().sendSMS(
					tel,
					URLEncoder.encode("上海邦尼驾驶短信验证码：", "gbk") + line
							+ URLEncoder.encode("，20分钟内有效哟~ >_<", "gbk"))) {
				mSoftCache.put(tel, new SoftReference<String>(line));
				Timer t = new Timer();
				final String mTel = tel;
				TimerTask tt = new TimerTask() {

					@Override
					public void run() {
						mSoftCache.remove(mTel);
					}
				};
				t.schedule(tt, 20 * 60 * 1000);
				return 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}

	public int userLogin(String acc, String psd) {
		String sql_is_exist = "SELECT id FROM t_hy WHERE sjh = " + acc;
		String sql_update_psd = "UPDATE t_hy SET pwd = ? WHERE id=?";
		String sql_add = "INSERT INTO t_hy (sjh,pwd) VALUES (?,?)";
		String sql_login = "SELECT id FROM t_hy WHERE sjh = ? AND pwd = ?";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			con.setAutoCommit(false);
			if (mSoftCache.containsKey(acc)) {
				System.out.println("contain key\n" + mSoftCache.get(acc).get());
				if (psd.equals(mSoftCache.get(acc).get())) {
					System.out.println("psd = value");
					Statement s = con.createStatement();
					ResultSet rs1 = s.executeQuery(sql_is_exist);
					String m_psd = mSoftCache.get(acc).get();
					if (rs1.next()) {
						int id = rs1.getInt(1);
						PreparedStatement ps = con
								.prepareStatement(sql_update_psd);
						ps.setString(1, m_psd);
						ps.setInt(2, id);
						ps.executeUpdate();
						con.commit();
						DBUtil.getInstance().closeConnection(con);
						return id;
					}
					PreparedStatement ps = con.prepareStatement(sql_add);
					ps.setString(1, acc);
					ps.setString(2, m_psd);
					ps.executeUpdate();
					s.clearBatch();
					s = con.createStatement();
					ResultSet rs2 = s.executeQuery(sql_is_exist);
					int id = -1;
					if (rs2.next())
						id = rs2.getInt(1);
					con.commit();
					DBUtil.getInstance().closeConnection(con);
					return id;
				}
			}
			int id = -1;
			PreparedStatement ps = con.prepareStatement(sql_login);
			ps.setString(1, acc);
			ps.setString(2, psd);
			ResultSet rs = ps.executeQuery();
			if (rs.next())
				id = rs.getInt(1);
			DBUtil.getInstance().closeConnection(con);
			return id;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtil.getInstance().closeConnection(con);
		return -1;
	}

}
